package com.calvin.combat.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.jar.JarEntry;

/**
 * Created by Calvin.Wang on 11/18/2014.
 */
public class LogHelper {

    public static void writeActionLog(final String folderPath, final String classMethod, String actionMessage) {
        writeLog(folderPath + "/Action", String.format("%1s-----%2s", classMethod, actionMessage));
    }

    public static void writeErrorLog(final String folderPath, final String classMethod, String errorMessage) {
        writeLog(folderPath + "/Error", String.format("%1s-----%2s", classMethod, errorMessage));
    }

    private static void writeFile(String filePath, String content) {
        File file = null;
        BufferedWriter writer = null;
        try {
            file = new File(filePath);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }

            if (file.getParentFile().isDirectory() && !file.exists()) {
                file.createNewFile();
            }

            if (!file.canWrite()) {
                file.setWritable(true);
            }

            writer = new BufferedWriter(new FileWriter(file, true));
            writer.write(String.format("%s\t--\t%s\n", SystemUtil.getCurrentDateTimeWithFormat("HH:mm:ss"), content));
            
        } catch (IOException io) {
            io.printStackTrace();
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }

    private static void writeLog(final String folderPath, String mag) {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        String fileName = String.format("%s.txt", dateFormat.format(date));
        String logPath = String.format("%1$s/%2$s", folderPath, fileName);
        writeFile(logPath, mag);
    }
}
